import { Table } from 'antd'
import {useEffect,useState} from 'react';

interface TableType {
  rowKey:string, //表格行 key 的取值，可以是字符串或一个函数
  row?:any, //表格行是否可选择，配置项
  columns:any, //表格列的配置描述
  showPage?:boolean, //是否使用分页
  pageSizeOptions?:number[],
  onPageChange?:Function, //页数更改
  getList:Function, //获取列表数据 api
  search?:any //检索
}

const pageInfoDefdata :PageType= {
  total:0,
  pageSize:20,
  page:1
}

export default function  MyTable  ({ rowKey,row, columns, pageSizeOptions, onPageChange,getList,search,showPage = true }:TableType){
  const [pageInfo,setPageInfo] = useState<PageType>(pageInfoDefdata);
  const [list,setList] = useState([])
  const [loading,setLoading] = useState(true)

  useEffect(() =>{
    setLoading(true)
    toGetList(pageInfo)
  },[]);
  // 获取列表
  const toGetList = async (newPageInfo:any) => {
    const res = await getList({...search,...newPageInfo});
    setPageInfo({total:res.total,pageSize:res.pageSize,page:res.page})
    setList(res.list)
    setLoading(false)
  }

// 默认分页切换
const toDefaultChange = (res: number) => {
  const newPageInfo = { ...pageInfo, page: res };
  setPageInfo(newPageInfo);
  setLoading(true);
  toGetList(newPageInfo);
};


  // 分页配置项
  const pagination = {
    showQuickJumper: true,
    total: pageInfo.total,
    pageSize: pageInfo.pageSize,
    current: pageInfo.page,
    showTotal: (total:any, range:any) => (<div>共{total}条</div>),
    pageSizeOptions: pageSizeOptions ? pageSizeOptions : [10, 20, 50, 100],
    onChange: onPageChange?onPageChange:toDefaultChange as any,
  }

  return (
    <div>
        <Table
          rowKey={rowKey}
          size='small'
          rowSelection={row ? row : {}}
          columns={columns}
          dataSource={list}
          pagination={showPage?pagination:false}
          loading={loading}
        />
      </div>
  )
}
